package com.bitters.controller;

import com.bitters.domain.RedPacketBasic;
import com.bitters.domain.RedPacketInfo;
import com.bitters.utils.RedPacketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author thomashe
 * @date 2023/11/15/ 15:32
 * @description
 */
@RestController
@RequestMapping("/redPacket")
@Slf4j
public class RedpacketController {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedPacketUtils redPacketUtils;

    /**
     * 发红包
     *
     * @param userId      用户id
     * @param totalAmount 红包总金额
     * @param totalPacket 红包总个数
     * @return
     */
    @PostMapping("/send")
    public String sendRedPackage(String userId, Integer totalAmount, Integer totalPacket) {
        // 组装数据
        RedPacketInfo info = new RedPacketInfo();
        info.setUserId(userId);
        info.setTotalAmount(totalAmount);
        info.setTotalPacket(totalPacket);
        info.setRemainingAmount(totalAmount);
        info.setRemainingPacket(totalPacket);
        info.setCreateTime(new Date());
        info.setUpdateTime(new Date());
        String redPacketId = UUID.randomUUID().toString();
        info.setRedPacketId(redPacketId);
        //TODO 红包保存到数据库

        //红包缓存
        RedPacketBasic redPacketBasic = new RedPacketBasic();
        redPacketBasic.setTotalPacket(totalPacket);
        redPacketBasic.setTotalAmount(totalAmount);

        // 抢红包资格缓存
        redisTemplate.opsForValue().set(RedPacketUtils.GRAB_RED_PACKAGE_KEY + redPacketId, totalAmount, RedPacketUtils.RED_PACKET_EXPIRE, TimeUnit.SECONDS);

        // 红包个数和总金额存入缓存
        redisTemplate.opsForValue().set(RedPacketUtils.RED_PACKAGE_KEY + redPacketId, redPacketBasic, RedPacketUtils.RED_PACKET_EXPIRE, TimeUnit.SECONDS);

        return "success";
    }

    /**
     * 抢红包，获取抢红包资格
     *
     * @param redPacketId 红包id
     * @param userId      用户id
     * @return
     */
    @PostMapping("/rob")
    public String rodRedPackage(String redPacketId, String userId) {

        String grabRedPacketId = RedPacketUtils.RED_PACKAGE_CONSUME_KEY + redPacketId;
        //1 验证某个用户是否抢过红包
        Object redPackage = redisTemplate.opsForHash().get(grabRedPacketId, userId);

        if (redPackage != null) {
            return "errorCode:-2,   message: " + "\t" + userId + " 用户你已经抢过红包了";
        }

        //没有抢过就有资格，否则表示抢过
        //红包的缓存key
        String redPacketKey = RedPacketUtils.RED_PACKAGE_KEY + redPacketId;
        RedPacketBasic redPacketBasic = (RedPacketBasic) redisTemplate.opsForValue().get(redPacketKey);
        if (redPacketBasic == null || redPacketBasic.getTotalPacket() <= 0) {
            //抢完
            return "errorCode:-1, 红包抢完了";
        }
        return "SUCCESS";
    }

    /**
     * 拆红包
     *
     * @param redPacketId 红包id
     * @param userId      用户id
     * @return
     */
    @PostMapping("/unpack")
    public Integer unpackRedPacket(String redPacketId, String userId) {
        // 预减获取红包剩余数量，decr原子减来防止领取人数超过红包个数
        Long decrement = redisTemplate.opsForValue().decrement(RedPacketUtils.GRAB_RED_PACKAGE_KEY + redPacketId, 1);
        if (decrement == null || decrement < 0) {
            log.info("拆红包失败, redPacketId:{}", redPacketId);
            throw new RuntimeException("红包被抢光了");
        }

        //拆红包
        Integer redPacketAmount = redPacketUtils.unpackRedPacket(redPacketId, userId);
        if (redPacketAmount == null || redPacketAmount == 0) {
            log.info("拆红包失败, redPacketId:{}", redPacketId);
            throw new RuntimeException("红包被抢光了");
        }

        //TODO 后续异步进mysql或者MQ进一步处理

        //TODO 插入抢红包记录, 并且扣减红包剩余金额和剩余个数

        return redPacketAmount;
    }
}
